package com.mproject.activity.project;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.provider.MediaStore.Audio.Playlists.Members;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.mproject.activity.Dashboard_ListProject;
import com.mproject.activity.R;
import com.mproject.adapter.Add_Member_Project_Info_Adapter;
import com.mproject.customclass.Project;
import com.mproject.customclass.UserAdded;
import com.mproject.network.IVLE_API_Helper;
import com.mproject.network.ProgressBarManager;

public class Project_Info_Add_Member extends Activity implements OnClickListener{

	private TextView add_member;
	private EditText member_id;
	private ListView member_added_list;
	private List<UserAdded> members;

	private TextView back_button;
	private TextView done_button;

	public static SharedPreferences mypref;
	Project project;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_member_project_info); 
		mypref=getSharedPreferences("My_Prefs",Activity.MODE_WORLD_WRITEABLE);

		Bundle extras=getIntent().getExtras();
		project=(Project) extras.getSerializable("project");

		add_member = (TextView)findViewById(R.id.add_member_info_button);
		add_member.setOnClickListener(this);
		member_id = (EditText)findViewById(R.id.add_member_project_info_member_id);
		member_added_list = (ListView)findViewById(R.id.add_member_info_list_added);

		back_button = (TextView)findViewById(R.id.add_member_project_info_back);
		back_button.setOnClickListener(this);
		done_button = (TextView)findViewById(R.id.add_member_project_info_save);
		done_button.setOnClickListener(this);
		members = new ArrayList<UserAdded>();
		Add_Member_Project_Info_Adapter adapter = new Add_Member_Project_Info_Adapter(Project_Info_Add_Member.this,getApplicationContext(), R.layout.add_member_list_added_row,members);
		member_added_list.setAdapter(adapter);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == add_member) {
			String userID = member_id.getText().toString();
			//validation
			if (userID.equals("")) {
				AlertDialog.Builder builder = new AlertDialog.Builder(Project_Info_Add_Member.this.getParent());
				builder.setMessage("Member ID cannot be empty!")
				.setNegativeButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}

				});
				AlertDialog alert = builder.create();
				alert.show();
				return;
			}
			if (isInTheList(userID)) {
				AlertDialog.Builder builder = new AlertDialog.Builder(Project_Info_Add_Member.this.getParent());
				builder.setMessage("This member ID already in the list!")
				.setNegativeButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}

				});
				AlertDialog alert = builder.create();
				alert.show();
				return;
			}
			members.add(new UserAdded(userID));
			member_id.setText("");
			refreshList();

		}
		if (v == back_button) {
			finish();
		}
		if (v == done_button) {
			loadingContent();
		}

	}

	public void refreshList() {
		member_added_list.invalidateViews();
	}

	//validate the current userID already in list or not.
	private boolean isInTheList (String userID) {
		for (UserAdded user : members) {
			if (user.getUserID().equals(userID)) {
				return true;
			}
		}
		return false;
	}

	public void loadingContent() {
		ProgressBarManager manager=new ProgressBarManager(Project_Info_Add_Member.this.getParent())
		{

			protected void onPreExecute() {

				Log.v("manager"," in pre execute");

				dialog.setMessage("Adding members please wait...");
				dialog.setIndeterminate(true);

				// dialog.setTitle("Manager");
				dialog.show();
			}

			protected Boolean doInBackground(String... params) 
			{

				try {
					String response = "";
					for (UserAdded member : members) {
						if (member.isManager()) 
							response = IVLE_API_Helper.addMemberToProject(mypref.getString("IVLE_Token", ""), project.getID(), member.getUserID(), "M");
						else
							response = IVLE_API_Helper.addMemberToProject(mypref.getString("IVLE_Token", ""), project.getID(), member.getUserID(), "R");
						if (response.indexOf("user ID is invalid.") > 0)
							member.setStatus("invalid");
						else 
							if (response.indexOf("is already a member of this community.") >0)
								member.setStatus("exist");
							else
								member.setStatus("success");
					}

					return true;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return false;
				}


			}
			protected void onPostExecute(Boolean result) {
				this.getDialog().dismiss();
				if (result == false) {
					AlertDialog.Builder builder = new AlertDialog.Builder(Project_Info_Add_Member.this.getParent());
					builder.setMessage("No internet connection")
					.setNegativeButton("OK", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
						}

					});
					AlertDialog alert = builder.create();
					alert.show();
				}
				else {
					List<UserAdded> invalid_user = new ArrayList<UserAdded>();
					List<UserAdded> exist_user = new ArrayList<UserAdded>();
					List<UserAdded> success_user = new ArrayList<UserAdded>();
					for (UserAdded user : members) {
						if (user.getStatus().equals("invalid"))
							invalid_user.add(user);
						if (user.getStatus().equals("exist"))
							exist_user.add(user);
						if (user.getStatus().equals("success"))
							success_user.add(user);
					}
					if (invalid_user.size() > 0) {
						String invalid_user_string = "";
						for (UserAdded user: invalid_user) {
							invalid_user_string += user.getUserID() + " ";						}
						AlertDialog.Builder builder = new AlertDialog.Builder(Project_Info_Add_Member.this.getParent());
						builder.setMessage(invalid_user_string+"is invalid user ID!")
						.setNegativeButton("OK", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}

						});
						AlertDialog alert = builder.create();
						alert.show();
					}

					if (exist_user.size() > 0) {
						String exist_user_string = "";
						for (UserAdded user: exist_user) {
							exist_user_string += user.getUserID() + " ";						}
						AlertDialog.Builder builder = new AlertDialog.Builder(Project_Info_Add_Member.this.getParent());
						builder.setMessage(exist_user_string+"is already a member of this community!")
						.setNegativeButton("OK", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}

						});
						AlertDialog alert = builder.create();
						alert.show();
					}
					if (success_user.size() > 0) {
						String success_user_string = "";
						for (UserAdded user: success_user) {
							members.remove(user);
							success_user_string += user.getUserID() + " ";						}
						AlertDialog.Builder builder = new AlertDialog.Builder(Project_Info_Add_Member.this.getParent());
						builder.setMessage(success_user_string+"is successfully added!")
						.setNegativeButton("OK", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
								member_added_list.invalidateViews();

							}

						});
						AlertDialog alert = builder.create();
						alert.show();
					}

					//fillProjectList();
				}
			}
		};
		manager.execute();
	}
}
